package com.conference.service.impl;

import com.conference.entity.UserConference;
import com.conference.entity.ConferenceVenue;
import com.conference.repository.UserConferenceRepository;
import com.conference.repository.ConferenceVenueRepository;
import com.conference.service.UserConferenceService;
import com.conference.dto.SeatUpdateDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserConferenceServiceImpl implements UserConferenceService {

    @Autowired
    private UserConferenceRepository userConferenceRepository;

    @Autowired
    private ConferenceVenueRepository conferenceVenueRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<UserConference> getConferenceSeats(Long conferenceId) {
        try {
            return userConferenceRepository.findByMeetingId(conferenceId);
        } catch (Exception e) {
            throw new RuntimeException("获取会议座位信息失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Map<String, Object> importSeats(Long conferenceId, List<UserConference> seats) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 删除原有的座位信息
            userConferenceRepository.deleteByMeetingId(conferenceId);
            
            // 设置会议ID并保存新的座位信息
            seats.forEach(seat -> seat.setMeetingId(conferenceId));
            List<UserConference> savedSeats = userConferenceRepository.saveAll(seats);
            
            result.put("success", true);
            result.put("message", "座位信息导入成功");
            result.put("data", savedSeats);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "座位信息导入失败: " + e.getMessage());
        }
        return result;
    }

    @Override
    public List<UserConference> getConferenceParticipants(Long conferenceId) {
        return userConferenceRepository.findByMeetingId(conferenceId);
    }

    @Override
    @Transactional
    public void updateVenueLayout(Long conferenceId, Long venueId, List<UserConference> participants) {
        try {
            // 构建座位布局数据
            Map<String, Object> layoutData = new HashMap<>();
            List<Map<String, Object>> rows = new ArrayList<>();
            
            // 按行号分组处理参会人员
            Map<Integer, List<UserConference>> participantsByRow = new HashMap<>();
            for (UserConference participant : participants) {
                participantsByRow
                    .computeIfAbsent(participant.getRowNum(), k -> new ArrayList<>())
                    .add(participant);
            }
            
            // 构建每一行的座位数据
            for (Map.Entry<Integer, List<UserConference>> entry : participantsByRow.entrySet()) {
                Map<String, Object> rowData = new HashMap<>();
                rowData.put("row", entry.getKey());
                
                List<Map<String, Object>> seats = new ArrayList<>();
                for (UserConference participant : entry.getValue()) {
                    Map<String, Object> seat = new HashMap<>();
                    seat.put("col", participant.getSeatNum());
                    seat.put("name", participant.getName());
                    seat.put("phone", participant.getPhone());
                    seat.put("email", participant.getEmail());
                    seats.add(seat);
                }
                
                rowData.put("seats", seats);
                rows.add(rowData);
            }
            
            layoutData.put("rows", rows);
            
            // 更新所有关联会议的场地布局
            List<ConferenceVenue> venues = conferenceVenueRepository.findByConferenceId(conferenceId);
            String layoutJson = objectMapper.writeValueAsString(layoutData);
            
            for (ConferenceVenue venue : venues) {
                venue.setLayoutData(layoutJson);
                conferenceVenueRepository.save(venue);
            }
            
        } catch (Exception e) {
            throw new RuntimeException("更新座位布局失败", e);
        }
    }

    @Override
    @Transactional
    public UserConference updateParticipantSeat(SeatUpdateDTO seatUpdateDTO) {
        // 先查找是否存在该座位的参会人员
        UserConference existingParticipant = userConferenceRepository.findByMeetingIdAndRowNumAndSeatNum(
            seatUpdateDTO.getMeetingId(),
            seatUpdateDTO.getRowNum(),
            seatUpdateDTO.getSeatNum()
        );

        UserConference participant;
        if (existingParticipant != null) {
            // 更新现有记录
            existingParticipant.setName(seatUpdateDTO.getName());
            existingParticipant.setPhone(seatUpdateDTO.getPhone());
            existingParticipant.setEmail(seatUpdateDTO.getEmail());
            participant = existingParticipant;
        } else {
            // 创建新记录
            participant = new UserConference();
            participant.setMeetingId(seatUpdateDTO.getMeetingId());
            participant.setRowNum(seatUpdateDTO.getRowNum());
            participant.setSeatNum(seatUpdateDTO.getSeatNum());
            participant.setName(seatUpdateDTO.getName());
            participant.setPhone(seatUpdateDTO.getPhone());
            participant.setEmail(seatUpdateDTO.getEmail());
        }

        return userConferenceRepository.save(participant);
    }

    @Override
    @Transactional
    public void deleteParticipantSeat(Long meetingId, Integer rowNum, Integer seatNum) {
        userConferenceRepository.deleteByMeetingIdAndRowNumAndSeatNum(meetingId, rowNum, seatNum);
    }
} 